import axios from 'axios'
import store from '../../store'
import {Message} from 'element-ui'
import {router} from '../../router'
axios.defaults.withCredentials = true

const apis = {
  // production: 'http://10.111.43.74:9090', // 线上 (生产环境)
  // development: 'http://10.111.43.74:9090', // 本地 (开发环境)
  production: 'http://127.0.0.1:9090', // 线上 (生产环境)
  development: 'http://127.0.0.1:9090', // 本地 (开发环境)
  accessHomeData: '' // 其他api
}
export const baseUrl = process.env.NODE_ENV === 'production' ? apis.production : apis.development

export const request = (options) => {
  return new Promise((resolve, reject) => {
    axios({
      method: options.method,
      url: `${baseUrl}${options.url}`,
      data: options.data,
      timeout: 6000,
      responseType: options.responseType ? options.responseType : 'json',
      params: options.params,
      transformRequest: [function (data) {
        if (options.noJson) { // 判断是否json格式或者是表单提交形式
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret // 便于直接取到内部data
        }
        return JSON.stringify(data)
      }],
      headers: {
        ...options.headers,
        'Content-Type': 'application/json',
        // eslint-disable-next-line no-undef
        'token': store.state.token
      }
    }).then(res => {
      if (options.getHeader) {
        resolve(res)
      } else {
        resolve(res.data)
      }
    }).catch(err => {
      const status = err.response.status
      if (status === 401) {
        Message.error('token失效，请重新登录')
        // 清除token
        localStorage.removeItem('loginToken')
        router.push('/login')
      }
      reject(err.data)
    })
  })
}

// uploadFileRequest  图片上传
export const uploadFileRequest = (url, data) => {
  return axios({
    method: 'post',
    url: `${baseUrl}${url}`,
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': store.state.token
    }
  })
}
// post
export const post = (options) => {
  options.method = 'post'
  options.data = options.params
  options.params = null
  return request(options)
}

// get
// responseType可以设置响应的数据类型为一个包含二进制数据的 Blob 对象,用于下载流文件
export const get = (options) => {
  options.method = 'get'
  options.data = null
  return request(options)
}
